import { Table, Button, message } from 'antd';
import { saveAs } from 'file-saver';
import React, { useEffect, useState } from 'react';
import { connect } from 'umi';

import type { ColumnType } from 'antd/es/table';

import type { OrderManageState } from '@/models/orderManage';
import { PRODCTION_NAME } from '@/pages/AddProductionLineUserNum';
import ContractModal from '@/pages/OrderManage/ContractModal';
import InvoiceModal from '@/pages/OrderManage/InvoiceModal';
// import OrderDetail from '@/pages/OrderManage/OrderDetail';
import { cancelOrderAction } from '@/services/orderManage';
import { getErrorMsg, priceFormat } from '@/util/utils';

import styles from './index.less';

interface Props {
  getList: any;
  data?: any;
  // '开具合同' | '申请合同'
  isIssueOrApply: string;
  // '开具发票' | 查看发票
  openOrSeeTicket: string;
  OrderManage: OrderManageState;
}

const USER_INFO = JSON.parse(localStorage.getItem('USER_INFO') as string);
const QMTable = (props: Props) => {
  const [dataSource, setDataSource] = useState<any>([]);

  // const [isOrderDetailVisible, setIsOrderDetailVisible] = useState<boolean>(false);
  const [isContractVisible, setIsContractVisible] = useState<boolean>(false);
  const [isInvoiceVisible, setIsInvoiceVisible] = useState<boolean>(false);
  // const [dataDetail, setDataDetail] = useState<any>({});

  const { openOrSeeTicket, getList } = props;
  //
  // const handleOrderDetail = (record: any) => {
  //   setIsOrderDetailVisible(true);
  //   setDataDetail({
  //     ...dataDetail,
  //     ...record,
  //   });
  //   console.log('handleOrderDetail>>>>>', record);
  // };

  useEffect(() => {
    setDataSource([props.data]);
    localStorage.setItem('PurchasedProducts', JSON.stringify(props.data));
  }, [props.OrderManage, props.data]);

  const payForOrder = () => {
    const currentOrder = props.data;
    localStorage.setItem('CURRENT_ORDER_INFO', JSON.stringify({
      companyName: USER_INFO?.companyName,
      // 支付的id为提交订单返回的id
      id: currentOrder.id,
      orderType: `芍园云安灯软件服务-${currentOrder.saasProduct.name}`,
      payYear: currentOrder.buyTimes,
      phone: USER_INFO?.mobileNo,
      price: currentOrder.unitPrice,
      productionLineNum: currentOrder.buyedProductionLineNumber,
      totalPrice: currentOrder.orderAmount,
      buyTimes: currentOrder.buyTimes,
      buyTimeUnitDesc: currentOrder.buyTimeUnitDesc,
      buyTimeUnit: currentOrder.buyTimeUnit,
    }));
    const timer = setTimeout(function() {
      try {
        window.open('/OrderPay');
        clearTimeout(timer);
      } catch (e) {
        console.log(e);
      }
    }, 0);
  };

  const cancelOrder = async () => {
    const id = props.data.id;
    const res = await cancelOrderAction(id);
    if (res.code===200) {
      getList();
      message.success('取消成功');
    } else {
      message.error(getErrorMsg(res));
    }
  };
  const columns: ColumnType<Record<string, any>>[] = [
    {
      title: '订购版本',
      dataIndex: 'orderVersion',
      key: 'orderVersion',
      render: (_: any, record: any) => PRODCTION_NAME + record?.saasProduct.name,
    },
    {
      title: '有效期至',
      dataIndex: 'expireDate',
      key: 'expireDate',
      width: 180,
      render: (_: any, record: any) => {
        return !record.expireDate ? '付款完成后开始计算' : record.expireDate;
      },
    },
    {
      title: '订购时长',
      dataIndex: 'buyTimes',
      key: 'buyTimes',
      render: (_: any, record: any) => {
        return record.buyTimes + (record.buyTimeUnitDesc);
      },
    },
    // {
    //   title: '订单金额（元）',
    //   dataIndex: 'paymentAmount',
    //   key: 'paymentAmount',
    // },
    {
      title: '订单类型',
      dataIndex: 'orderTypeDesc',
      key: 'orderTypeDesc',
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      render: (_: any, record: any): string => {
        switch (_ || record?.status) {
          case 0:
            return '未生效';
          case 1:
            return '已取消';
          case 2:
            return '已关闭';
          case 3:
            return '已生效';
          default:
            return '';
        }
      },
    },
    {
      title: '申请合同',
      dataIndex: 'isInvoiced',
      key: 'isContract',
      render: (_: any, record: any) => record.isContract ? '已申请' : '未申请',
    },
    {
      title: '是否开票',
      dataIndex: 'isInvoiced',
      key: 'isInvoiced',
      render: (_: any, record: any) => record.isInvoiced ? '已开票' : '未开票',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      render: () => {
        return (
          <div className={styles.tableOperation}>
            {
              <>
                <Button disabled={props.data.status !== 0 || props.data.orderType===3} type="link" onClick={cancelOrder}>取消订单</Button>
                <Button disabled={props.data.status !== 0 || props.data.orderType===3} type="link" onClick={payForOrder} style={{ marginLeft: 5 }}>支付</Button>
              </>
            }
          </div>
        );
      },
    },
  ];
  const handleDownloadContractNo = () => {
    const contractFile = props.data.contractFile;
    if (!!contractFile) {
      const fileType = contractFile.split('.')[1];
      saveAs(window.location.origin + `/images/${contractFile}`, `订单合同.${fileType}`);
    } else {
      message.info('工作人员处理中, 稍后再试');
    }
  };
  return (
    <div className={styles.index}>
      <InvoiceModal
        openOrSeeTicket={openOrSeeTicket}
        isInvoiceVisible={isInvoiceVisible}
        setIsInvoiceVisible={setIsInvoiceVisible}
      />
      <ContractModal
        title={'申请合同'}
        isContractVisible={isContractVisible}
        setIsContractVisible={setIsContractVisible}
      />
      {/*<OrderDetail*/}
      {/*  dataDetail={dataDetail}*/}
      {/*  isOrderDetailVisible={isOrderDetailVisible}*/}
      {/*  setIsOrderDetailVisible={setIsOrderDetailVisible}*/}
      {/*/>*/}
      <Table rowKey={'id'} dataSource={dataSource} columns={columns} pagination={false}/>
      <div className={styles.orderMoney} style={ props.data?.status !== 3 ? { justifyContent: 'end' } : { justifyContent: 'space-between' } }>
        <div/>
        <div className={styles.fonts}><span className={styles.contractNo}>
          合同号：<span style={{ cursor: 'pointer', color: '#1A3DC9' }} onClick={() => {handleDownloadContractNo();}}>{props.data.contractNo ?? ''}</span></span>
          订单金额： <span className={styles.amount}>￥{priceFormat(Number(props.data.orderAmount))}</span>
        </div>
      </div>
      {/*<div className={styles.operation}>*/}
      {/*  <div/>*/}
      {/*  {*/}
      {/*    props.data.status === 0 &&*/}
      {/*    <div className={styles.rightButtons}>*/}
      {/*      <Button type="link" onClick={cancelOrder}>取消订单</Button>*/}
      {/*      <Button type="primary" onClick={payForOrder}>支付</Button>*/}
      {/*    </div>*/}
      {/*  }*/}
      {/*</div>*/}
    </div>
  );
};
const mapState = ({ OrderManage }: { OrderManage: OrderManageState }) => {
  return {
    OrderManage,
  };
};
export default connect(mapState)(QMTable);
